<?php

	class purchases {
		

		function purchases() {
			global $admin;

			//if(empty($_SESSION["managerid"])) $admin->login();
		}
		
		function index() {
			global $admin,$db,$config;
			if ($_POST['act']=='export'){
			    $params=$_GET;
			   $sqlstr = "select id,shop,product,spec,unit,pricebuy,number,(number*pricebuy) as zongjian,FROM_UNIXTIME(timestocked,'%Y-%m-%d %H:%i:%s' )as buptime,puser,suser from {$config->db_prefix}purchases where 1=1";
			if (!empty($params['id'])) $sqlstr .= " and id = ".$db->qstr($params['id']);
			if (!empty($params['productid'])) $sqlstr .= " and productid = ".$db->qstr($params['productid']);
			if (!empty($params['shopid'])) $sqlstr .= " and shopid = ".$db->qstr($params['shopid']);
			if (!empty($params['keywords'])) $sqlstr .= " and (productid=". $db->qstr($params['keywords']) ." or product like ". $db->qstr("%".$params['keywords']."%") .")";
			if (!empty($params['sdate'])) $sqlstr .= " and thedate>=". strtotime($params['sdate']);
			if (!empty($params['edate'])) $sqlstr .= " and thedate<=". strtotime($params['edate']);
			if (!empty($params['lprice'])) $sqlstr .= " and pricebuy>=". $db->qstr($params['lprice']);
			if (!empty($params['hprice'])) $sqlstr .= " and pricebuy<=". $db->qstr($params['hprice']);
			if (!empty($params['lnumber'])) $sqlstr .= " and number>=". $db->qstr($params['lnumber']);
			if (!empty($params['hnumber'])) $sqlstr .= " and number<=". $db->qstr($params['hnumber']);
			
			if (!empty($params['supplier'])) $sqlstr .= " and supplier like ". $db->qstr("%".$params['supplier']."%");
				
			if (!empty($params['lotnumber'])) $sqlstr .= " and lotnumber like ". $db->qstr("%".$params['lotnumber']."%");
			if (!empty($params['sdate1'])) $sqlstr .= " and timeexpress>=". strtotime($params['sdate1']);
			if (!empty($params['edate1'])) $sqlstr .= " and timeexpress<=". strtotime($params['edate1']);
			if (!empty($params['sdate2'])) $sqlstr .= " and timeend>=". strtotime($params['sdate2']);
			if (!empty($params['edate2'])) $sqlstr .= " and timeend<=". strtotime($params['edate2']);
			if (!empty($params['sdate3'])) $sqlstr .= " and timestocked>=". strtotime($params['sdate3']);
			if (!empty($params['edate3'])) $sqlstr .= " and timestocked<=". strtotime($params['edate3']);
				
			
			if (!empty($params['cond'])) $sqlstr .= " and ({$params['cond']})";
			
			if($params['type']!==null&&$params['type']!==''){
			     $sqlstr .= " and type= {$params['type']}";
			}
			
			if($params['status']==="0"){
			    $sqlstr .= " and timestocked= 0";
			}elseif ($params['status']==="1"){
			    $sqlstr .= " and timestocked> 0";
			}elseif ($params['status']==="-1"){
			    $sqlstr .= " and timestocked= -1";
			}
				
			
			if (!empty($params['counter'])) $counter = $db->getrow(str_replace("*", "sum(number) number, sum(pricebuy*number) price", $sqlstr));
			if (!empty($params['order'])) $sqlstr .= " order by {$params['order']}";
			    include_once '../lib/php_excel.php';
			    $export_data=$db->GetArray($sqlstr);
			    $queue[0] = array("序号","仓库","产品名称","规格","单位","单价","采购数量","总价","采购时间","采购员"," 入库员");//定义表头
			    $export_data = array_merge($queue,$export_data);
			   /*  print_r($export_data);
			    exit; */
			    $filename =   "采购信息" . date ( "YmdHis" );
			    $xls = new Excel_XML ( 'UTF-8', false, '采购信息' );
			    $xls->addArray ( $export_data );
			    $xls->generateXML ( $filename );
			    exit ();
			}
			//if(!$admin->rights("purchases_view")) return;
		}


		function create() {
			global $db, $smarty, $config, $segment, $admin;
			//if(!$admin->rights("purchases_create")) return;
			
			if(!empty($_POST["action"]) && $_POST["action"]=="create") {
					$paper_id = intval($_POST['paper_id']);
					$title   = @mysql_real_escape_string($_POST["title"]);
					$shopid   = intval($_POST["shopid"]);
					$supplierid = intval($_POST["supplierid"]);
					$memo = @mysql_real_escape_string($_POST["memo"]);
// 					$purchase_price = $_POST['purchase_price'];
					$discount_price = $_POST['discount_price'];
					$express_price 	= $_POST['express_price'];
					$other_price 	= $_POST['other_price'];
					$currency_unit 	= $_POST['currency_unit'];
					$products = json_decode(stripslashes($_POST["products"]),true);
					if(empty($shopid) || empty($supplierid) || empty($title))
					{
						exit('illegal post data');
					}
					if(empty($products) || !is_array($products))
					{
						exit('illegal products data');
					}
					foreach($products as $v)
					{
						$unit = @mysql_real_escape_string($v['unit']);
						$pricebuy = floatval($v['pricebuy']);
						$number = intval($v['number']);
						if($pricebuy<=0)
						{
							exit('采购价格必须大于0');
						}
						if(empty($unit))
						{
							exit('单位不能为空');
						}
						if($number<1)
						{
							exit('采购数量必须大于0');
						}
					}
					
					$sql = "SELECT `title` FROM `haiou_stock_shops` WHERE `id`=$shopid";
					$shop = $db->GetOne($sql);
					$sql = "SELECT `title` FROM `haiou_stock_suppliers` WHERE `id`=$supplierid";
					$supplier = $db->GetOne($sql);
					if(empty($shop) || empty($supplier))
					{
						exit('illegal shopid or supplier');
					}
					
					
					$puser=$db->qstr($_SESSION['ADMIN_USER']);

					//插入表模板表中
					if($paper_id>0)
					{
						//更新采购表
						$sql = "SELECT  `id`,`title`,`shopid`,`shop`,`supplierid`,`create_time`,`puser`,`status` FROM `haiou_stock_purchases_paper` WHERE id={$paper_id}";
						$paper = $db->GetRow($sql);
						if(empty($paper))
						{
							exit('没有找到此采购单');
						}
						if($paper['status']=='1')
						{
							exit('此采购单价已入库，不能再编辑！');
						}
						if($paper['status']=='2')
						{
							exit('此采购单已有部分商品入库，不能再编辑！');
						}
						
						$sqlstr = "UPDATE {$config->db_prefix}purchases_paper SET `title`='{$title}',`shopid`='{$shopid}',`supplierid`='{$supplierid}', `supplier`='{$supplier}',`shop`='{$shop}',`memo`='{$memo}',`discount_price`='{$discount_price}',`express_price`='{$express_price}',`other_price`='{$other_price}',`currency_unit`='{$currency_unit}',`is_update_price`=0 WHERE `id`={$paper_id}";
						$result = $db->execute($sqlstr);
						$parentId = $paper_id;
						
						//清除已有的
						$sqlstr = "DELETE FROM {$config->db_prefix}purchases WHERE `paper_id`={$paper_id}";
						$result = $db->execute($sqlstr);
					}
					else 
					{
						//插入
						$nowDate = date('Y-m-d H:i:s');
						$sqlstr = "insert into {$config->db_prefix}purchases_paper (`title`,`shopid`,`supplierid`, `shop`,`supplier`,`memo`,`discount_price`,`express_price`,`other_price`, `puser`, `create_time`,`status`,`currency_unit`) values ('{$title}','{$shopid}', '{$supplierid}','{$shop}','{$supplier}','{$memo}','{$discount_price}','{$express_price}','{$other_price}',$puser,'{$nowDate}',0,'{$currency_unit}')";
						$result = $db->execute($sqlstr);
						$parentId = $db->Insert_ID();
					}
					
					if($parentId==false)
					{
						exit('insert db faild');
					}
					
					//插入商品数据
					#去重 
					$loop = $products;
					$products = array();
					foreach($loop as $v)
					{
						$products[$v['id']] = $v;
					}
					ksort($products);
					#组装插入SQL
					$inArr = array();
					$values = '';
					foreach($products as $v)
					{
						$skuId = intval($v['id']);
						$unit = @mysql_real_escape_string($v['unit']);
						$pricebuy = floatval($v['pricebuy']);
						$discount = floatval($v['discount']);
						$number = intval($v['number']);
						$productInfo = $db->getRow("SELECT `pname`,`catid`,`brandid` FROM `haiou_product_sku` WHERE `id`={$skuId}");
						if(empty($productInfo))
						{
							continue;
						}
						$product = @mysql_escape_string($productInfo['pname']);
						$currency_unit = @mysql_escape_string($v['currency_unit']);
						$catid = $productInfo['catid'];
						$brandid = $productInfo['brandid'];
						$inArr[] = array(
										'paper_id'=>$parentId,
										'productid'=>$skuId,
										'product'=>$product,
										'shopid'=>$shopid,
										'shop'=>$shop,
										'supplierid'=>$supplierid,
										'supplier'=>$supplier,
										'unit'=>$unit,
										'pricebuy'=>$pricebuy,
										'discount'=>$discount,
										'currency_unit'=>$currency_unit,
										'number'=>$number,
										'puser'=>str_replace('\'','',$puser),
										'extension'=>array('brandid'=>$brandid,'catid'=>$catid)
						);
					}
					
					//按指定顺序排序：品牌放一堆，然后分类放一堆
					$tempInArr = array();
					foreach($inArr as $k=>$v){
						$brandid = $v['extension']['brandid'];
						$catid = $v['extension']['catid'];
						unset($v['extension']);
						$tempInArr[$brandid][$catid][] = $v;
					}
					$inArr = array();
					foreach($tempInArr as $v){
						foreach($v as $vv){
							foreach($vv as $vvv){
								$inArr[] = $vvv;
							}
						}
					}
					foreach($inArr as $v){
						$values .= '(\''.implode("','", $v).'\'),';
					}
					
					$values = substr($values, 0,strlen($values)-1);
					$sql = "INSERT INTO `haiou_stock_purchases`(`paper_id`,`productid`,`product`,`shopid`,`shop`,`supplierid`,`supplier`,`unit`,`pricebuy`,`discount`,`currency_unit`,`number`,`puser`) VALUES {$values}";
					$result = $db->execute($sql);
					if(!$result)
					{
						exit('faild2');
					}
					//完成后更新采购单表is_update_price字段以触发更新采购总价和商品实际采购单价
					$sql = "update {$config->db_prefix}purchases_paper set `is_update_price`=1 where `id`={$parentId}";
					$db->execute($sql);
					exit('ok');
				}
								
				if(!empty($errors)) $smarty->assign("errors", $errors);
		}
		
		/**
		 * 搜索商品数据
		 */
			function recaches()
		{
			global $db, $smarty, $config, $segment, $admin;
			$inputValues = $_POST['inputValue'];
			$barcodeValues = $_POST['barcode'];
			$supplierid = $_POST['supplierid'];
			$inputValues = str_replace('，', ',', $inputValues);
			$pidTempArr = explode(',', $inputValues);
			$pidArr = array();
			foreach($pidTempArr as $v)
			{
				$v = intval($v);
				if($v>0)
				{
					$pidArr[] = $v;
				}
			}
			$pidStr = implode(',', $pidArr);
			if(!empty($pidStr)){
				$pidWhere = " AND pid IN({$pidStr}) ";
			}else{
				$pidWhere = "";
			}
			/**条码**/
			$barcodeValues = str_replace('，', ',', $barcodeValues);
			$barcodeTempArr = explode(',', $barcodeValues);
			$barcodeArr = array();
			foreach($barcodeTempArr as $v)
			{
				if($v>0)
				{
					$barcodeArr[] = $v;
				}
			}
			$barcodeStr = implode(',', $barcodeArr);
			/**条码**/
			if(!empty($barcodeStr)){
				$barcodeWhere = " AND hsp.barcode IN({$barcodeStr}) ";
			}else{
				$barcodeWhere = "";
			}
			//供应商条件
			$supplieridWhere = " AND hssp.supplieid=0";
			if($supplierid>0){
			    //判断供应商是否为通用供应商，是则条件改为对应仓库
			    $sql = "select is_general,shopid from {$config->db_prefix}suppliers where id={$supplierid} limit 1";
			    $supplierInfo = $db->GetRow($sql);
			    if(!empty($supplierInfo) && $supplierInfo['is_general']==1){
			        $supplieridWhere = " AND hssp.shopid={$supplierInfo['shopid']}";
			    }else{
    			    $supplieridWhere = " AND hssp.supplieid={$supplierid}";
			    }
			}
			$sql = "SELECT hps.id,hps.pid,hps.pname,hps.stock,hps.price,hps.spec,hps.pic,hssp.pricebuy AS cost_price,hssp.shopid,hssp.currency_unit,hsp.barcode FROM haiou_product_sku AS hps LEFT JOIN haiou_stock_supplie_products AS hssp ON hssp.product_sku_id=hps.id JOIN haiou_stock_products AS hsp ON hsp.product_sku_id=hps.id where 1 {$pidWhere}{$supplieridWhere}{$barcodeWhere} AND `hps`.`status`!=-9 ORDER BY pid DESC";
			$result = $db->GetArray($sql);
			if($result){
				//拆分图片
				foreach($result as $k=>$v)
				{
					$picArr = explode(',', $v['pic']);
					$result[$k]['pic'] = "<img src='{$picArr[0]}/80'>";
				}
				
				$arr = array('total'=>count($result),'rows'=>$result);
			}else{
				$arr = array();
			}
			$jsonResult = json_encode($arr);
			exit($jsonResult);
		}
		
		
		function modify() {
			global $db, $smarty, $config, $segment, $admin;
			
			//获取编辑的数据
			$purchases_id = intval($_GET['purchases_id']);
			if($purchases_id<=0)
			{
				exit('无效的purchases_id');
			}
			$sql = "SELECT  `id`,`title`,`shopid`,`shop`,`memo`,`purchase_price`,`discount_price`,`express_price`,`other_price`,`supplierid`,`create_time`,`puser`,`status` FROM `haiou_stock_purchases_paper` WHERE id={$purchases_id}";
			$paper = $db->GetRow($sql);
			if(empty($paper))
			{
				exit('没有找到此采购单');
			}
			if($paper['status']=='-1')
			{
				exit('此采购单价已被删除');
			}
			if($paper['status']=='1')
			{
				exit('此采购单已审核，不能再编辑！');
			}
			if($paper['status']=='9')
			{
				exit('此采购单已入库，不能再编辑！');
			}
			if($paper['status']!='0')
			{
				exit('此采购单状态限制不能编辑！');
			}
			
			$smarty->assign('paper',$paper);
			$sql = "SELECT  hps.`id`,hps.`pic`,hps.`pid`,hps.`pic`,hps.`pname`,hps.`spec`,hsp.`unit`,hsp.`pricebuy`,hsp.`discount`,hsp.`number`,hsp.currency_unit FROM `haiou_stock_purchases` AS hsp LEFT JOIN haiou_product_sku AS hps ON hps.id=hsp.productid  WHERE paper_id={$purchases_id} ORDER BY hsp.`id` ASC";
			$products = $db->GetArray($sql);
			foreach($products as $k=>$v)
			{
				$picArr = explode(',', $v['pic']);
				$products[$k]['pic'] = "<img src='{$picArr[0]}/80'>";
			}
			$productData = array('total'=>count($products),'rows'=>$products);
			$smarty->assign('productData',json_encode($productData));
			
			if(!empty($errors)) $smarty->assign("errors", $errors);
		}


		function remove() {
			global $db, $segment, $config, $admin;
			//if(!$admin->rights("purchases_delete")) return;

			$id = $db->qstr($_GET['purchases_id']);
			
			$sql = "SELECT  `status` FROM `haiou_stock_purchases_paper` WHERE id={$id}";
			$paper = $db->GetRow($sql);
			if(empty($paper))
			{
				exit('没有找到此采购单');
			}
			if($paper['status']=='-1')
			{
				exit('此采购单价已被删除');
			}
			if($paper['status']=='1')
			{
				exit('此采购单已审核，不能再删除！');
			}
			if($paper['status']=='9')
			{
				exit('此采购单已入库，不能删除！');
			}
			if($paper['status']!='0')
			{
				exit('此采购单状态限制不能删除！');
			}
			
			$sqlstr = "delete from {$config->db_prefix}purchases_paper where id=$id";
			$result = $db->execute($sqlstr);
			if($result)
			{
				$sqlstr = "delete from {$config->db_prefix}purchases where paper_id=$id";
				$result = $db->execute($sqlstr);
			}
			if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=purchases.php":$_SERVER['HTTP_REFERER']));
		}
		
		/**
		 * 审核采购单
		 */
		function audit()
		{
			global $db, $segment, $config, $admin;
			$purchases_id = intval($_GET['purchases_id']);
			if(!($purchases_id>0))
			{
				exit('参数purchases_id错误');
			}
				
			$id = $db->qstr($_GET['purchases_id']);
			$sql = "SELECT  `status` FROM `haiou_stock_purchases_paper` WHERE id={$id}";
			$paper = $db->GetRow($sql);
			if(empty($paper))
			{
				exit('没有找到此采购单');
			}
			if($paper['status']=='-1')
			{
				exit('此采购单价已被删除');
			}
			if($paper['status']!='0')
			{
				exit('此采购单状态不能置为已审核！');
			}
			
			$sqlstr = "UPDATE {$config->db_prefix}purchases_paper SET `status`=1 WHERE `id`={$id}";
			$result = $db->execute($sqlstr);
			if($result)
			{
				header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=purchases.php":$_SERVER['HTTP_REFERER']));
			}
			else
			{
				exit('系统错误，请重试');
			}
		}
		
		/**
		 * 确认采购单
		 */
		function confirm(){
			global $db, $segment, $config, $admin;
			$purchases_id = intval($_GET['purchases_id']);
			if(!($purchases_id>0))
			{
				exit('参数purchases_id错误');
			}
			
			$id = $db->qstr($_GET['purchases_id']);
			$sql = "SELECT  `status` FROM `haiou_stock_purchases_paper` WHERE id={$id}";
			$paper = $db->GetRow($sql);
			if(empty($paper))
			{
				exit('没有找到此采购单');
			}
			if($paper['status']=='-1')
			{
				exit('此采购单价已被删除');
			}
			if($paper['status']!='1')
			{
				exit('此采购单状态不能置为确认状态！');
			}
				
			$sqlstr = "UPDATE {$config->db_prefix}purchases_paper SET `status`=2 WHERE `id`={$id}";
			$result = $db->execute($sqlstr);
			if($result)
			{
				header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=purchases.php":$_SERVER['HTTP_REFERER']));
			}
			else
			{
				exit('系统错误，请重试');
			}
		}
		
		/**
		 * 加载供应商
		 */
		function getSupplies(){
			global $db;
			$classid = intval($_REQUEST['classid']);
			$shopid = intval($_REQUEST['shopid']);
			$where = 'WHERE 1';
			if($classid>0)
			{
				$where .= " AND  classid={$classid}";
			}
			if($shopid>0)
			{
				$where .= " AND  shopid={$shopid}";
			}
			$sql = "SELECT  `id`,`title` FROM `haiou_stock_suppliers` {$where	}";
			$list = $db->GetArray($sql);
			$json = json_encode($list);
			exit($json);
		}
		
		/**
		 * 加载订单采购商品
		 */
		function getOrderProducts(){
			global $db;
			$supplierid = intval($_REQUEST['supplierid']);
			if($supplierid<=0){
				$json = json_encode(array('total'=>0,'rows'=>array()));
				exit($json);
			}
			//方案一：定义查询时的分界时间
// 			$splitHours1 = '15:30:00';
// 			$splitHours2 = '22:30:00';
// 			$nowTime = time();
// 			$splitTime1 = strtotime(date("Y-m-d {$splitHours1}"));
// 			$splitTime2 = strtotime(date("Y-m-d {$splitHours2}"));
// 			if($nowTime<$splitTime1){
// 				$splitTime = strtotime('-1 day',$splitTime2);
// 			} else if($nowTime<$splitTime2){
// 				$splitTime= $splitTime1;
// 			}else{
// 				$splitTime = $splitTime2;
// 			}

			//方案二：某时间点以前的
			$splitTime = strtotime('-5 minute');
			
			//查询库存不足的订单商品id
			$sql = "SELECT `hso`.`productid` AS `resultId`,SUM(`hso`.`number`) AS `number` FROM 
				`haiou_stock_orders` AS `hso` 
				 LEFT JOIN `haiou_stock_products` AS `hsp` ON `hsp`.`product_sku_id`=`hso`.`productid` 
				 WHERE FIND_IN_SET('$supplierid',`hsp`.`supplieid`) AND `hso`.`thedate`<{$splitTime} AND `hso`.`timestocked`=0 
			     GROUP BY `hso`. `productid`
			     HAVING `number`>(
			     										(SELECT IFNULL((SELECT `stocks` FROM `haiou_stock_stocks` AS `Shss` WHERE `Shss`.`productid`=`resultId`),0))
			     										+
			     										(SELECT IFNULL((SELECT SUM(`SShsp`.`number`) FROM `haiou_stock_purchases` AS `SShsp` WHERE `SShsp`.`productid`=`resultId` AND `timeexpress`=0  GROUP BY(`SShsp`.`productid`)),0))
													)
				";
			$orderProducts = $db->GetArray($sql);
			if(empty($orderProducts)){
				$json = json_encode(array('total'=>0,'rows'=>array()));
				exit($json);
			}
			//根据ID查询详细信息
			$needProducts = array();
			$productsIdStr = '';
			foreach($orderProducts as $v){
				if($productsIdStr!=''){
					$productsIdStr .= ',';
				}
				$productsIdStr .= $v['resultId'];
				$needProducts[$v['resultId']] = $v['number'];
			}
			$sql = "SELECT hps.id,hps.pid,hps.pname,hps.price,hps.spec,hps.pic,hsp.pricebuy AS cost_price ,IFNULL(`hss`.`stocks`,0) AS `stocks`
								FROM haiou_product_sku AS hps 
								LEFT JOIN haiou_stock_products AS `hsp` ON `hsp`.`product_sku_id`=`hps`.`id` 
								LEFT JOIN `haiou_stock_stocks` AS `hss` ON `hss`.`productid`=`hps`.`id`
								where `hps`.`id` IN({$productsIdStr})  ORDER BY `pid` DESC";
			$result = $db->GetArray($sql);
			//计算库存差值
			$sql = "SELECT `productid`,SUM(`number`) AS `number` FROM `haiou_stock_purchases` WHERE `productid`  IN({$productsIdStr}) AND `timeexpress`=0 GROUP BY(`productid`)";
			$resultPurchases = $db->GetArray($sql);
			$purchases = array();
			foreach($resultPurchases as $v){
				$purchases[$v['productid']] = $v['number'];
			}
			foreach($result as $k=>$v){
				if(!empty($purchases[$v['id']])){
					$result[$k]['number'] = $needProducts[$v['id']] - $v['stocks'] - $purchases[$v['id']];
				}else{
					$result[$k]['number'] = $needProducts[$v['id']] - $v['stocks'];
				}
			}
			//拆分图片
			foreach($result as $k=>$v)
			{
				$picArr = explode(',', $v['pic']);
				$result[$k]['pic'] = "<img src='{$picArr[0]}/80'>";
			}
			$resultArr = array('total'=>count($result),'rows'=>$result);
			$json = json_encode($resultArr);
			exit($json);
		}
		
		/**
		 * 获取采购单的商品信息
		 */
		function getPurchasesProductList(){
			global $db, $segment, $config, $admin;
			$id = $db->qstr($_GET['purchases_id']);
			$sql = "select hss.*,hps.pname,hps.pid,hps.pic,hpc.cat as cat_name,hsps.barcode from {$config->db_prefix}purchases as hss left join haiou_product_sku as hps on hss.productid=hps.id left join haiou_product_cat as hpc on hps.catid=hpc.catid LEFT JOIN haiou_stock_products AS hsps ON hsps.product_sku_id=hss.productid where hss.paper_id={$id} order by hss.id asc";
			$res = $db->GetArray($sql);
			$str = '<tr><td colspan="14"><table width="100%" border="1" cellspacing="0" cellpadding="0" id="sku_list">
      <tr id="title">
        <td>产品ID</td>
        <td>条码数字</td>
		<td>产品图片</td>
        <td>产品名称</td>
        <td>产品分类</td>
        <td>规格</td>
        <td>单位</td>
        <td>单价</td>
        <td>采购数量</td>
        <td>总价</td>
        <td>总折扣</td>
        <td>实际单价</td>
        <td>实际总价</td>
        <td>采购时间</td>
        <td>入库状态</td>
        <td>采购员</td>
        <td>入库员</td>
      </tr>';
		
			if(empty($res)){
				$str .="<tr><td colspan='11' align='center'>未选择任何商品</td></tr>";
			}else{
				foreach($res as $val){
					$timestocked = "";
					if($val['timestocked']>0){
						$status = "已入库";
						$timestocked = date("Y-m-d H:i:s",$val["timestocked"]);
					}elseif($val['timestocked']==0){
						$status = "未处理";
					}else{
						$status = "未入库";
					}
					$picArr = explode(',', $val['pic']);
					$pic = "<a href=\"{$picArr[0]}\" target=\"_blank\"><img src=\"{$picArr[0]}/80\" /></a>";
					$str .= '      <tr id="content" purchases_id='.$val['id'].'>
	        <td>'.$val["pid"].'</td>
	        <td>'.$val["barcode"].'</td>
	        <td>'.$pic.'</td>
	        <td>'.$val["pname"].'</td>
	        <td>'.$val["cat_name"].'</td>
	        <td>'.$val["spec"].'</td>
	        <td>'.$val["unit"].'&nbsp;</td>
	        <td><span class="purchases_price">'.$val["pricebuy"].'</span>'.$val["currency_unit"].'</td>
	        <td>'.($val["number"]+0).'</td>
	        <td style="color: red"><span>'.round($val["pricebuy"]*$val["number"],2).'</span>'.$val["currency_unit"].'</td>
	        <td><span class="purchases_product_discount">'.$val['discount'].'</span></td>
	        <td>'.$val['realpricebuy'].'</td>
	        <td style="color: red"><span>'.round($val["pricebuy"]*$val["number"]-$val['discount'],2).'</span>'.$val["currency_unit"].'</td>
	        <td>'.$timestocked.'</td>
	        <td>'.$status.'</td>
	        <td>'.$val["puser"].'</td>
	        <td>'.$val["suser"].'</td>
	      </tr>';
				}
			}
		
			$str .= "</table></td></tr>";
			die($str);
		}
		
		function stockconfirm(){
		    global $db, $segment, $config, $smarty;
		    $purchaseid = $db->qstr($_GET['purchases_id']);
		    $rss = $db->getrow("select * from {$config->db_prefix}purchases where id=$purchaseid and timestocked=0");
		    if($rss) {
		        $shopid = $db->qstr($rss["shopid"]);
		        $shop = $db->qstr($rss["shop"]);
		        $productid = $db->qstr($rss["productid"]);
		        $product = $db->qstr($rss["product"]);
		        $spec = $db->qstr($rss["spec"]);
		        $unit = $db->qstr($rss["unit"]);
		        $number = $rss["number"]+0;
		         
		        
		        $stockid = $db->getone("select id from {$config->db_prefix}stocks where shopid=$shopid and productid=$productid");
		        if(!$stockid)$sqlstr = "insert into {$config->db_prefix}stocks (shopid, shop, productid, product, spec, unit, stocks) values ($shopid, $shop, $productid, $product, $spec, $unit, $number)";
		        else $sqlstr = "update {$config->db_prefix}stocks set stocks=stocks+$number where id=$stockid";
		        $result = $db->execute($sqlstr);
		        $this->_update_product_stocks($productid);
		         
		        $timestocked = time();
		        $sqlstr = "update {$config->db_prefix}purchases set timestocked=$timestocked where id=$purchaseid";
		        $result = $db->execute($sqlstr);
		        if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=purchases.php":$_SERVER['HTTP_REFERER']));
		    }
		}
		
		function stockcancel(){
		    global $db, $segment, $config, $smarty;
		    $purchaseid = $db->qstr($_GET['purchases_id']);
		    $sqlstr = "update {$config->db_prefix}purchases set timestocked=-1 where id=$purchaseid";
		    $result = $db->execute($sqlstr);
		    if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=purchases.php":$_SERVER['HTTP_REFERER']));
		    
		    
		}
		
		function _update_product_stocks($productid) {
		    global $db, $segment, $config, $smarty;
		    	
		    $stocks = $db->getone("select sum(stocks) from {$config->db_prefix}stocks where productid=$productid");
		    if(!$stocks) $stocks = 0;
		    $result = $db->execute("update {$config->db_prefix}products set stocks=$stocks where id=$productid");
		    return $result;
		}
		
		function sctock() {
		    global $db, $segment, $config, $smarty, $admin;
		    //if(!$admin->rights("income_view")) return;
		
		    if(!empty($segment[1]) && $segment[1]=="confirm") {
		        if(!$admin->rights("income_modify")) return;
		
		        $purchaseid = $db->qstr($segment[2]);
		        $rss = $db->getrow("select * from {$config->db_prefix}purchases where id=$purchaseid and timestocked=0");
		        if($rss) {
		            $shopid = $db->qstr($rss["shopid"]);
		            $shop = $db->qstr($rss["shop"]);
		            $productid = $db->qstr($rss["productid"]);
		            $product = $db->qstr($rss["product"]);
		            $spec = $db->qstr($rss["spec"]);
		            $unit = $db->qstr($rss["unit"]);
		            $number = $rss["number"]+0;
		            	
		            //
		            $stockid = $db->getone("select id from {$config->db_prefix}stocks where shopid=$shopid and productid=$productid");
		            if(!$stockid)$sqlstr = "insert into {$config->db_prefix}stocks (shopid, shop, productid, product, spec, unit, stocks) values ($shopid, $shop, $productid, $product, $spec, $unit, $number)";
		            else $sqlstr = "update {$config->db_prefix}stocks set stocks=stocks+$number where id=$stockid";
		            $result = $db->execute($sqlstr);
		            $this->_update_product_stocks($productid);
		            	
		            $timestocked = time();
		            $sqlstr = "update {$config->db_prefix}purchases set timestocked=$timestocked where id=$purchaseid";
		            $result = $db->execute($sqlstr);
		            if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_index}admin/stocks/income":$_SERVER['HTTP_REFERER']));
		        }
		    }
		    	
		    elseif(!empty($segment[1]) && $segment[1]=="cancel") {
		        if(!$admin->rights("income_modify")) return;
		
		        $purchaseid = $db->qstr($segment[2]);
		        $rss = $db->getrow("select * from {$config->db_prefix}purchases where id=$purchaseid and timestocked!=0");
		        if($rss) {
		            $shopid = $db->qstr($rss["shopid"]);
		            $productid = $db->qstr($rss["productid"]);
		            $number = $rss["number"]+0;
		            	
		            //
		            $stock = $db->getrow("select * from {$config->db_prefix}stocks where shopid=$shopid and productid=$productid");
		            if(!$stock) $errors["unexisted_product"] = true;
		            else if($stock["stocks"]<$number) $errors["notenough_stocks"] = true;
		            else if($stock["stocks"]==$number) $sqlstr = "delete from {$config->db_prefix}stocks where id=". $stock['id'];
		            else $sqlstr = "update {$config->db_prefix}stocks set stocks=stocks-$number where id=". $stock['id'];
		            	
		            if(empty($errors)) {
		                $result = $db->execute($sqlstr);
		                $this->_update_product_stocks($productid);
		                $sqlstr = "update {$config->db_prefix}purchases set timestocked=0 where id=$purchaseid";
		                $result = $db->execute($sqlstr);
		                if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_index}admin/stocks/income":$_SERVER['HTTP_REFERER']));
		            }
		            	
		            if(!empty($errors)) $smarty->assign("errors", $errors);
		        }
		    }
		    	
		}
		
		function updatePrice(){
			global $db, $segment, $config, $smarty;
			$id = intval($_POST['purchases_id']);
			$price = floatval($_POST['price']);
			$discount = floatval($_POST['discount']);
			
// 			exit(''.$id.'-'.$pid.'-'.$price);
			
			$arr = array('code'=>'-1','msg'=>'保存失败');
			if($id>0 && ($price>0 || $discount>0)){
				//查询所属采购单ID
				$sql = "select paper_id from {$config->db_prefix}purchases where id={$id}";
				$paper = $db->GetRow($sql);
				//先把采购单表is_update_price字段更新为0
				$sql = "update {$config->db_prefix}purchases_paper set is_update_price=0 where id={$paper['paper_id']}";
				$db->execute($sql);
				if($price>0){
					//更新采购商品单价
					$sqlstr = "update {$config->db_prefix}purchases set pricebuy=$price where id=$id";
					$result = $db->execute($sqlstr);
				}
				if($discount>0){
					//更新采购商品单价
					$sqlstr = "update {$config->db_prefix}purchases set discount=$discount where id=$id";
					$result = $db->execute($sqlstr);
				}
				//把采购单表is_update_price字段更新为1以触发更新采购总价和商品实际采购单价
				$sql = "update {$config->db_prefix}purchases_paper set is_update_price=1 where id={$paper['paper_id']}";
				$db->execute($sql);
				$arr = array('code'=>0,'msg'=>'success');
			}
			$json = json_encode($arr);
			exit($json);
		}

		/**
		 * 需要采购商品列表
		 */
		function orderProducts(){
			global $db, $segment, $config, $smarty;
			$where = "";
			$storeWhere = "";
			if($_GET['shopid']>0){
				$where .= " AND `hso`.`shopid`='{$_GET['shopid']}'";
			}else{
				$_GET['shopid'] = 1;
				$where .= " AND `hso`.`shopid`='1'";
			}
			if(!$_GET['listType']){
				$_GET['listType'] = 2;
			}
// 			if($_GET['classid']>0){
// 				$where .= " AND `hsp`.`classid`='{$_GET['classid']}' ";
// 			}
			if($_GET['supplierid']>0){
				$where .= " AND FIND_IN_SET('{$_GET['supplierid']}',`hsp`.`supplieid`)";
				$storeWhere .= " AND FIND_IN_SET('{$_GET['supplierid']}',`hsp1`.`supplieid`)";
			}
			if($_GET['sdate']){
				$sdate = strtotime($_GET['sdate']." 00:00:00");
				$where .= " AND `hso`.`thedate`>{$sdate}";
			}
			if($_GET['edate']){
				$edate = strtotime($_GET['edate']." 23:59:59");
				$where .= " AND `hso`.`thedate`<{$edate}";
			}
			
			$sql = "SELECT `hso`.`productid` AS `resultId`,SUM(`hso`.`number`) AS `number` FROM
			`haiou_stock_orders` AS `hso`
			LEFT JOIN `haiou_stock_products` AS `hsp` ON `hsp`.`product_sku_id`=`hso`.`productid`
			WHERE (`hso`.`type`=0 or `hso`.`type`=5) {$where} AND `hso`.`timestocked`=0
			GROUP BY `hso`. `productid`
			HAVING `number`>(
			(SELECT IFNULL((SELECT `stocks` FROM `haiou_stock_stocks` AS `Shss` WHERE `Shss`.`productid`=`resultId` and `Shss`.shopid={$_GET['shopid']}),0))
			+
			(SELECT IFNULL((SELECT SUM(`SShsp`.`number`) FROM `haiou_stock_purchases` AS `SShsp` WHERE `SShsp`.`productid`=`resultId` AND `SShsp`.shopid={$_GET['shopid']} AND `timeexpress`=0  GROUP BY(`SShsp`.`productid`)),0))
			)
			";

			$orderProducts = $db->GetArray($sql);//订单采购
			
			if($_GET['listType']==1){
				//备货采购
				$sql = "SELECT `hsp1`.`product_sku_id` AS `resultId`,`hsp1`.`shopwarningnum`,IFNULL(`hss`.`stocks`,0) AS stock,(SELECT IFNULL((SELECT SUM(`hso`.`number`) FROM `haiou_stock_orders` AS `hso` LEFT JOIN `haiou_stock_products` AS `hsp` ON `hsp`.`product_sku_id`=`hso`.`productid` WHERE `hso`.`productid`=`hsp1`.`product_sku_id` AND `hso`.`timestocked`=0 {$where}),0)) AS order_num
				FROM `haiou_stock_products` AS	`hsp1`
				LEFT JOIN `haiou_stock_stocks` AS `hss` ON `hsp1`.`product_sku_id`=`hss`.`productid` AND `hss`.`shopid`={$_GET['shopid']}
				LEFT JOIN `haiou_product_sku` AS `hps` ON `hps`.`id`=`hsp1`.`product_sku_id`
				WHERE `hsp1`.`shopid`={$_GET['shopid']} AND `hps`.`status`>0 {$storeWhere}
				HAVING (
				stock
				-order_num
				+(SELECT IFNULL((SELECT SUM(`SShsp`.`number`) FROM `haiou_stock_purchases` AS `SShsp` WHERE `SShsp`.`productid`=`hsp1`.`product_sku_id` AND `SShsp`.shopid={$_GET['shopid']} AND `timeexpress`=0  GROUP BY(`SShsp`.`productid`)),0))
				)<`hsp1`.`shopwarningnum`";
				
				$storeProducts = $db->GetArray($sql);
				
				$sql = "select `sku_id` as `resultId`,sum(`num`) as totalNum from ".MICROSTOCK." where stock_shop='{$_GET['shopid']}' GROUP BY sku_id HAVING totalNum>0";
				$microStockProducts = $db->GetArray($sql);//微仓采购
				
				if(empty($orderProducts) && empty($storeProducts) && empty($microStockProducts)){
					$res = array('total'=>0,'rows'=>array());
					$smarty->assign('list',$res);return;
				}
			}else{
			    $sql = "select `sku_id` as `resultId`,sum(`num`) as totalNum from ".MICROSTOCK." where stock_shop='{$_GET['shopid']}' GROUP BY sku_id HAVING totalNum>0";
			    $microStockProducts = $db->GetArray($sql);//微仓采购
			    
				if(empty($orderProducts) && empty($microStockProducts)){
					$res = array('total'=>0,'rows'=>array());
					$smarty->assign('list',$res);return;
				}
			}
			
			$needProducts = array();
			$microStockNeedProducts = array();
			$productsIdStr = '';
			if($_GET['listType']==2){
    			//订单采购
    			foreach($orderProducts as $v){
    				if($productsIdStr!=''){
    					$productsIdStr .= ',';
    				}
    				$productsIdStr .= $v['resultId'];
    				$needProducts[$v['resultId']] = $v['number'];
    			}
    			
    			if(!empty($microStockProducts)){
    			    foreach($microStockProducts as $mv){
    			        if(empty($needProducts[$mv['resultId']])){
    			            if($productsIdStr!=''){
    			                $productsIdStr .= ',';
    			            }
    			            $productsIdStr .= $mv['resultId'];
    			        }
    			        $microStockNeedProducts[$mv['resultId']] = $mv['totalNum'];
    			    }
    			}
			}
			if($_GET['listType']==1){//备货采购
				if(!empty($storeProducts)){
					foreach($storeProducts as $sv){
						if(empty($needProducts[$sv['resultId']])){
							if($productsIdStr!=''){
								$productsIdStr .= ',';
							}
							$productsIdStr .= $sv['resultId'];
							$needProducts[$sv['resultId']] = $sv['order_num'];
						}
					}
				}
				if(!empty($microStockProducts)){
				    foreach($microStockProducts as $mv){
				        if(empty($needProducts[$mv['resultId']])){
				            if($productsIdStr!=''){
				                $productsIdStr .= ',';
				            }
				            $productsIdStr .= $mv['resultId'];
				        }
				        $microStockNeedProducts[$mv['resultId']] = $mv['totalNum'];
				    }
				}
			}
			
			//根据ID查询详细信息
			$sql = "SELECT hps.id,hps.pid,hps.pname,hps.price,hps.spec,hps.pic,hps.`status`,hsp.pricebuy AS cost_price ,IFNULL(`hss`.`stocks`,0) AS `stocks`,`hsp`.`shopwarningnum`,`hsp`.`currency_unit`
			FROM haiou_product_sku AS hps
			LEFT JOIN haiou_stock_products AS `hsp` ON `hsp`.`product_sku_id`=`hps`.`id`
			LEFT JOIN `haiou_stock_stocks` AS `hss` ON `hss`.`productid`=`hps`.`id` and `hss`.shopid={$_GET['shopid']}
			where `hps`.`id` IN({$productsIdStr}) ORDER BY `pid` DESC";
			$result = $db->GetArray($sql);
			//计算库存差值
			$sql = "SELECT `productid`,SUM(`number`) AS `number` FROM `haiou_stock_purchases` WHERE `productid`  IN({$productsIdStr}) AND `shopid`={$_GET['shopid']} AND `timeexpress`=0 GROUP BY(`productid`)";
			$resultPurchases = $db->GetArray($sql);
			$purchases = array();
			foreach($resultPurchases as $v){
			$purchases[$v['productid']] = $v['number'];
			}
			foreach($result as $k=>$v){
				$purchases[$v['id']] = empty($purchases[$v['id']])?0:$purchases[$v['id']];
				$result[$k]['purchasesNum'] = $purchases[$v['id']];
				$shopwarningnum = ($v['status']<=0)?0:$v['shopwarningnum'];
				$result[$k]['number'] = $needProducts[$v['id']] - $v['stocks'] - $purchases[$v['id']] + $shopwarningnum;
				$order_num = $needProducts[$v['id']] - $v['stocks'] - $purchases[$v['id']];
				
				$result[$k]['order_num'] = ($order_num>=0)?$order_num:0;
				$result[$k]['warningNum'] = ($result[$k]['number']>0?$result[$k]['number']:0) - $result[$k]['order_num'];
				$result[$k]['microStockNeedNum'] = empty($microStockNeedProducts[$v['id']])?0:$microStockNeedProducts[$v['id']];
				$leftStocks = ($v['stocks'] + $purchases[$v['id']] - $shopwarningnum - $needProducts[$v['id']]);
				$result[$k]['microStockNum'] = ($leftStocks>0)?$result[$k]['microStockNeedNum']-$leftStocks:$result[$k]['microStockNeedNum'];
				$result[$k]['number'] = $result[$k]['number']+$result[$k]['microStockNeedNum'];
			}
			//拆分图片
			$resArr = array();
			foreach($result as $k=>$v)
			{
			    $picArr = explode(',', $v['pic']);
				$v['pic'] = "<img src='{$picArr[0]}/80'>";
				if($v['number']>0){
				    $resArr[$k] = $v;
				}
			}
			$resultArr = array('total'=>count($resArr),'rows'=>$resArr);
// 			$json = json_encode($resultArr);
// 			exit($json);
			$smarty->assign('list',$resultArr);
			unset($_GET['m']);
			unset($_GET['s']);
			$smarty->assign('print_param',http_build_query($_GET));
		}

}
?>